package com.iqiyi.pps.epg.api.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class HttpUtils {

	private static HttpClient httpClient;

	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	private static HttpClient getHttpClient() {
		if (httpClient == null) {
			httpClient = new HttpClient();
			HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
			httpClient.setHttpConnectionManager(httpConnectionManager);

			// 设置60s超时
			httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(20 * 1000);
			httpClient.getHttpConnectionManager().getParams().setSoTimeout(20 * 1000);
		}
		return httpClient;
	}

	public static String sendGet(String urlString) throws IOException {
		return getFrom(urlString, null, null);
	}

	public static String sendGet(String urlString, Map<String, Object> params) throws IOException {
		return getFrom(urlString, params, null);
	}

	public static String sendGet(String urlString, Map<String, Object> params, Map<String, Object> headers)
			throws IOException {
		return getFrom(urlString, params, headers);
	}

	public static String sendPost(String urlString) throws IOException {
		return postJSONTo(urlString, null, null);
	}

	public static String sendPost(String urlString, String parametersJsonString) throws IOException {
		return postJSONTo(urlString, null, parametersJsonString);
	}

	// get
	private static String getFrom(String httpUrl, Map<String, Object> params, Map<String, Object> headers)
			throws HttpException, IOException {
		String result = null;
//		logger.info("HTTP Get From URL:{} With param:{} and headers:{}", new Object[] { httpUrl, params, headers });
		
		GetMethod get = new GetMethod(_getUrl(httpUrl, params));
		if (headers != null) {
			for (String headerName : headers.keySet()) {
//				get.getParams().setParameter(headerName, String.valueOf(headers.get(headerName)));
				get.setRequestHeader(headerName, String.valueOf(headers.get(headerName)));
			}
		}
		
		HttpClient client = getHttpClient();
		int code = 0;
		try {
			code = client.executeMethod(get);
			if (code >= 200 && code < 300)
				result = get.getResponseBodyAsString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}

		logger.info("HTTP Get From URL:{} With param:{} And Response with code:{} and response:{}", new Object[] {
				httpUrl, params, code, result });
		return result;
	}

	private static String _getUrl(String httpUrl, Map<String, Object> params) throws UnsupportedEncodingException {
		StringBuilder sb = new StringBuilder();
		if (params != null && params.size() > 0)
			for (String paramName : params.keySet()) {
				String _spliter = "&";
				if (sb.length() == 0) {
					if (httpUrl.indexOf("?") == -1) {
						_spliter = "?";
					}
				}
				sb.append(_spliter);
				sb.append(URLEncoder.encode(paramName, "UTF-8"));
				sb.append("=");
				if (params.get(paramName) != null) {
					sb.append(URLEncoder.encode(params.get(paramName).toString(), "UTF-8"));
				}
			}
		return httpUrl + sb.toString();
	}

	private static String postJSONTo(String httpUrl, Map<String, Object> params, String body) throws HttpException,
			IOException {
		String result = null;
//		logger.info("HTTP POST From URL:{} With param:{} and body {}", new Object[] { httpUrl, params, body });
		PostMethod post = new PostMethod(_getUrl(httpUrl, params));
		StringRequestEntity entity = new StringRequestEntity(body, "application/json", "UTF-8");
		post.setRequestEntity(entity);
		HttpClient client = getHttpClient();
		int code = 0;
		try {
			code = client.executeMethod(post);
			if (code >= 200 && code < 300)
				result = post.getResponseBodyAsString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}

		logger.info("HTTP Post to URL:{} With param:{} And Response with code:{} and response:{}", new Object[] {
				httpUrl, params, code, result });
		return result;
	}

	public static JSONObject HTTPGetJsonObject(String httpUrl) throws IOException {
		String s = getFrom(httpUrl, null, null);
		JSONObject jsonObject = JSONObject.parseObject(s);
		return jsonObject;
	}

	/*
	 * http请求返回JSONArray
	 */
	public static JSONArray HTTPGetJsonArray(String httpUrl) throws IOException {
		// System.out.println(urlString);
		String s = getFrom(httpUrl, null, null);
		JSONArray jsonArray = JSONArray.parseArray(s);
		return jsonArray;
	}
	
	public static JSONArray HTTPGetJsonArray(String httpUrl , Map<String, Object> params) throws IOException {
		// System.out.println(urlString);
		String s = getFrom(httpUrl, params, null);
		JSONArray jsonArray = JSONArray.parseArray(s);
		return jsonArray;
	}

	public static void main(String[] args) throws Exception {
		String r;
		// r =
		// sendGet("http://operation.lego.pps.tv:8080/pps-operation/episode/get.action?id=31");
		// System.out.println(r);
		r = sendPost(
				"http://operation.lego.pps.tv:8080/pps-operation/episode/save.action",
				"{\"ppsBaseData\":{\"areaTag\":\"15\",\"channelId\":\"2\",\"checkLastUpdate\":\"1\",\"contentType\":\"1\",\"displayName\":\"节目显示名\",\"enableThirdSpider\":\"1\",\"exclusive\":\"1\",\"ppsCatrgoryId\":[\"69\"],\"ppsWikiId\":\"36092\",\"promptDescription\":\"\",\"qipuId\":732843500,\"reviewMethod\":\"0\",\"shortDisplayName\":\"\",\"typeTag\":\"20,21,23,24,27,29\",\"wikiTag\":\"104,106,104,106\"},\"ppsSetting\":[{\"area\":\"\",\"download\":1,\"listType\":0,\"onlineTime\":\"\",\"platformId\":0,\"status\":1},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":1},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":2},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":3},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":4},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":5},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":6},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":7},{\"area\":\"\",\"listType\":0,\"onlineTime\":\"\",\"platformId\":8}]}");
		System.out.println(r);
	}
}
